package com.soufang.soufangdemo.controller;

import com.soufang.soufangdemo.base.ApiResponse;
import com.soufang.soufangdemo.base.SecurityUser;
import com.soufang.soufangdemo.dto.UserDTO;
import com.soufang.soufangdemo.entity.User;
import com.soufang.soufangdemo.repository.UserRepository;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/users")
public class UserController {

    private UserRepository userRepository;

    public UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
    
    @GetMapping("/info")
    public ApiResponse<UserDTO> getUserInfo() {
        SecurityUser securityUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = securityUser.getUsername();
        User user = userRepository.findByName(username);
        UserDTO dto = new UserDTO();
        dto.setAvatar(user.getAvatar());
        dto.setEmail(user.getEmail());
        dto.setId(user.getId());
        dto.setCreateTime(user.getCreateTime());
        dto.setStatus(user.getStatus());
        dto.setLastLoginTime(user.getLastLoginTime());
        dto.setName(user.getName());
        return ApiResponse.success(dto);
    }
}
